<template>
    <div class="service_container">
        <el-form ref="" :model="service" label-width="60%" label-position="top">
            <h2>服务详情编辑</h2>
            <el-form-item label="视频类展示">
                <video-player v-show="playerOptions.sources[0].src != ''" class="video-player vjs-custom-skin"
                    :options="playerOptions"></video-player>
                <el-upload :accept="uploadVideo.accept" ref="uploadVideo" action="uploadUrl" :limit="1"
                    :http-request="handleUpload" :file-list="uploadVideo.fileList" :on-success="handleVideoSuccess"
                    :on-remove="handleVideoRemove" :on-exceed="handleVideoExceed" :data="imgUploadData['video']">
                    <el-button ref="video" slot="trigger" size="small" type="primary">选取视频文件</el-button>
                    <el-button style="margin-left: 10px;" v-show="playerOptions.sources[0].src != ''" size="small"
                        type="danger" @click="handleVideoRemove">撤销视频</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传MP4文件,且不超过10M</div>
                </el-upload>
            </el-form-item>
            <el-form-item label="服务名称">
                <el-input type="text" v-model="service.serviceName" placeholder="请输入服务名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="服务描述">
                <el-input type="text" v-model="service.serviceDescribe" placeholder="请输入服务描述" clearable></el-input>
            </el-form-item>
            <el-form-item label="展示价/起单费用">
                <el-input type="number" v-model="service.commission" placeholder="请输入展示价格" clearable></el-input>
            </el-form-item>
            <el-form-item label="特征/优势">
                <el-input type="text" v-model="service.characteristic[0]" placeholder="请输入服务优势" clearable></el-input>
                <el-input type="text" v-model="service.characteristic[1]" placeholder="请输入服务优势" clearable></el-input>
                <el-input type="text" v-model="service.characteristic[2]" placeholder="请输入服务优势" clearable></el-input>
            </el-form-item>
            <el-form-item label="封面图">
                <el-image v-show="uploadCoverImg.currentImg != ''"
                    style="width: 150px; height: 150px;background-color: #f2f2f2;"
                    :src="baseUrl + uploadCoverImg.currentImg" fit="contain"></el-image>
                <el-upload list-type="text" :accept="uploadCoverImg.accept" ref="uploadCoverImg" action="uploadUrl"
                    :http-request="handleUpload" :limit="1" :file-list="uploadCoverImg.fileList"
                    :on-success="handleCoverImgSuccess" :on-remove="handleCoverImgRemove" :on-exceed="handleCoverImgExceed"
                    :data="imgUploadData['coverImg']">
                    <el-button ref="coverImg" slot="trigger" size="small" type="primary">选择服务封面图</el-button>
                    <el-button style="margin-left: 10px;" v-show="uploadCoverImg.fileList.length > 0" size="small"
                        type="danger" @click="handleCoverImgRemove">撤销上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-form-item>
            <el-form-item label="轮播图">
                <div class="img-list">
                    <div class="img-item" v-for="img in uploadSwiperImg.currentImgs">
                        <el-image style="width: 150px; height: 150px;background-color: #f2f2f2;" :src="baseUrl + img"
                            fit="scale-down">
                        </el-image>
                        <span class="el-upload-list__item-actions" @click=handleSwiperImgRemove(img)>
                            <span class="el-upload-list__item-preview" @click="">
                                <i class="el-icon-circle-close"></i>
                            </span>
                        </span>
                    </div>
                </div>
                <el-upload ref="uploadSwiperImg" :accept="uploadSwiperImg.accept" :multiple="true" action="uploadUrl"
                    :http-request="handleUpload" :file-list="uploadSwiperImg.fileList" :on-success="handleSwiperImgSuccess"
                    :on-remove="handleSwiperImgRemove" :data="imgUploadData['swiperImg']">
                    <el-button ref="swiperImg" slot="trigger" size="small" type="primary">选择轮播图</el-button>
                    <el-button style="margin-left: 10px;" v-show="uploadSwiperImg.fileList.length > 0" size="small"
                        type="danger" @click="handleSwiperImgRemove">撤销上传/更改</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-form-item>
            <el-form-item label="服务详情">
                <div class="img-list">
                    <div class="img-item" v-for="img in uploadDetailImg.currentImgs">
                        <el-image style="width: 150px; height: 150px;background-color: #f2f2f2;" :src="baseUrl + img"
                            fit="scale-down">
                        </el-image>
                        <span class="el-upload-list__item-actions" @click=handleDetailImgRemove(img)>
                            <span class="el-upload-list__item-preview" @click="">
                                <i class="el-icon-circle-close"></i>
                            </span>
                        </span>
                    </div>
                </div>
                <el-upload ref="uploadDetailImg" :accept="uploadDetailImg.accept" :multiple="true" action="uploadUrl"
                    :http-request="handleUpload" :file-list="uploadDetailImg.fileList" :on-success="handleDetailImgSuccess"
                    :on-remove="handleDetailImgRemove" :data="imgUploadData['detailsImg']">
                    <el-button slot="trigger" size="small" type="primary">选择详情图</el-button>
                    <el-button style="margin-left: 10px;" v-show="uploadDetailImg.fileList.length > 0" size="small"
                        type="danger" @click="handleDetailImgRemove">撤销上传/更改</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-form-item>
            <el-form-item label="服务提示">
                <el-input type="text" v-model="service.serviceTips" placeholder="请输入服务提示" clearable></el-input>
            </el-form-item>
            <el-form-item label="服务时长选择" prop="delivery">
                <el-switch v-model="serviceTime"></el-switch>
            </el-form-item>
            <el-form-item label="服务时长设置" v-show="serviceTime">
                起始值：<el-input type="number" v-model="service.serviceTimeStart" placeholder="请输入服务时长起始值，例：1 --> 1小时"
                    clearable></el-input>
                间隔值：<el-input type="number" v-model="service.serviceTimeStep" placeholder="请输入服务时长间隔值" clearable></el-input>
                选择项数：<el-input type="number" v-model="service.serviceTimeNum" placeholder="请输入服务时长选择项数"
                    clearable></el-input>
                <el-form-item label="服务时长提示(按顺序)" prop="delivery">
                    <el-input type="text" v-for="(item, index) in  service.serviceTimeNum / 1 "
                        v-model="service.serviceTimeTips[index]" :placeholder="'请输入' + getTime(index) + '小时提示'"
                        clearable></el-input>
                </el-form-item>
            </el-form-item>
            <el-form-item label="精品推荐展示图（点击选择）">
                主图
                <div class="img-item" style="width: 100px;">
                    <el-upload class="avatar-uploader" action="uploadUrl" :show-file-list="false"
                        :http-request="handleUpload" :data="imgUploadData['recommendationImgBig']">
                        <el-image v-if="service.recommendationImg.bigImg"
                            style="width: 100px; height: 100px;background-color: #f2f2f2;"
                            :src="baseUrl + service.recommendationImg.bigImg" fit="contain" />
                        <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"></i>
                    </el-upload>
                    <span class="el-upload-list__item-actions" v-show="service.recommendationImg.bigImg"
                        @click=handleReBigImgRemove>
                        <span class="el-upload-list__item-preview" @click="">
                            <i class="el-icon-circle-close"></i>
                        </span>
                    </span>
                </div>
                次图
                <div class="img-list">
                    <div class="img-item">
                        <el-upload class="avatar-uploader" action="uploadUrl" :show-file-list="false"
                            :http-request="handleUpload" :data="imgUploadData['recommendationImgSmallO']">
                            <el-image v-if="service.recommendationImg.smallImg[0]"
                                style="width: 100px; height: 100px;background-color: #f2f2f2;"
                                :src="baseUrl + service.recommendationImg.smallImg[0]" fit="contain" />
                            <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"></i>
                        </el-upload>
                        <span class="el-upload-list__item-actions" v-show="service.recommendationImg.smallImg[0]"
                            @click=handleReSmallImg1Remove>
                            <span class="el-upload-list__item-preview">
                                <i class="el-icon-circle-close" style="font-size: 20px;"></i>
                            </span>
                        </span>
                    </div>
                    <div class="img-item">
                        <el-upload class="avatar-uploader" action="uploadUrl" :show-file-list="false"
                            :http-request="handleUpload" :data="imgUploadData['recommendationImgSmallT']">
                            <el-image v-if="service.recommendationImg.smallImg[1]"
                                style="width: 100px; height: 100px;background-color: #f2f2f2;"
                                :src="baseUrl + service.recommendationImg.smallImg[1]" fit="contain" />
                            <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"></i>
                        </el-upload>
                        <span class="el-upload-list__item-actions" v-show="service.recommendationImg.smallImg[1]"
                            @click=handleReSmallImg2Remove>
                            <span class="el-upload-list__item-preview">
                                <i class="el-icon-circle-close" style="font-size: 20px;"></i>
                            </span>
                        </span>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="热门服务展示图（点击选择）">
                <div class="img-item" style="width: 100px;">
                    <el-upload class="avatar-uploader" action="uploadUrl" :show-file-list="false"
                        :http-request="handleUpload" :data="imgUploadData['popularImg']">
                        <el-image v-if="service.popularServicesImg"
                            style="width: 100px; height: 100px;background-color: #f2f2f2;"
                            :src="baseUrl + service.popularServicesImg" fit="contain" />
                        <i v-else class="el-icon-plus avatar-uploader-icon" style="font-size: 30px;"></i>
                    </el-upload>
                    <span class="el-upload-list__item-actions" v-show="service.popularServicesImg"
                        @click=handleHotImgRemove>
                        <span class="el-upload-list__item-preview" @click="">
                            <i class="el-icon-circle-close"></i>
                        </span>
                    </span>
                </div>
            </el-form-item>
            <el-form-item size="large">
                <el-button type="primary" @click="submit()">保存</el-button>
                <el-button @click="reset()">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'
import { updateService, addService } from '@/api/miniprogram/service'
import { uploadImgToCloud, uploadImgPre } from "@/api/menu";
export default {
    name: "Service",
    components: {
        videoPlayer
    },
    props: {
        serviceParams: {},
        submitService: Function
    },
    data() {
        return {
            videoLoading: false,
            baseUrl: process.env.VUE_APP_IMG_BASE_URL,
            service: this.serviceParams,
            oldService: {},
            //视频播放器配置
            playerOptions: {
                playbackRates: [0.5, 1.0, 1.5, 2.0],
                autoplay: false,
                muted: false,//默认情况下消除任何音频
                loop: false, //是否循环
                preload: 'auto', //浏览器在加载<video>元素后就下载视频数据
                language: 'zh-CN',
                aspectRatio: '16:9',//将播放器置于流畅模式，并在计算播放器的动态大小时使用改值，值应该代表一个比例
                fluid: true,//player是否拥有流体大小（按比例缩放适应容器）
                notSupportedMessage: '此视频暂无法播放，请稍后再试',
                controlBar: {
                    timeDivider: true,
                    durationDisplay: true,
                    remainingTimeDisplay: false,
                    fullscreenToggle: true  // 全屏按钮
                },
                sources: [{
                    type: "video/mp4",// 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
                    src: '', // url地址
                    name: ''
                }],
            },
            //上传参数
            imgUploadData: {
                "video": { type: "video" },
                "detailsImg": { type: "detailsImg" },
                "coverImg": { type: "coverImg" },
                "swiperImg": { type: "swiperImg" },
                "recommendationImgBig": { type: "recommendationImg", size: "b" },
                "recommendationImgSmallO": { type: "recommendationImg", size: "s1" },
                "recommendationImgSmallT": { type: "recommendationImg", size: "s2" },
                "popularImg": { type: "popularImg" }
            },
            //上传视频参数
            uploadVideo: {
                fileList: [],
                accept: 'video/*',
            },
            //上传封面图参数
            uploadCoverImg: {
                currentImg: "",
                fileList: [],
                accept: 'image/*'
            },
            //上传轮播图参数
            uploadSwiperImg: {
                currentImgs: [],
                fileList: [],
                accept: 'image/*'
            },
            //上传详情图参数
            uploadDetailImg: {
                currentImgs: [],
                fileList: [],
                accept: 'image/*'
            },
            //是否有服务时长
            serviceTime: false,
        }
    },
    created() {
        this.initService();
    },
    methods: {
        //服务详情初始化
        initService() {
            this.uploadVideo.fileList = [];
            this.uploadCoverImg.fileList = [];
            this.uploadSwiperImg.fileList = [];
            this.uploadDetailImg.fileList = [];

            this.oldService = JSON.parse(JSON.stringify(this.service));
            this.playerOptions.sources[0].src = this.service.videoUrl ? this.baseUrl + this.service.videoUrl : '';
            this.playerOptions.sources[0].name = this.service.videoUrl ? this.service.videoUrl : '';
            this.uploadCoverImg.currentImg = this.service.serviceCoverImg || "";
            this.uploadSwiperImg.currentImgs = JSON.parse(JSON.stringify(this.service.swiperImgUrls)) || [];
            this.uploadDetailImg.currentImgs = JSON.parse(JSON.stringify(this.service.serviceDetailsUrls)) || [];
            this.serviceTime = this.service.serviceTime == 1 || false;

            this.service.recommendationImg = this.service.recommendationImg || { bigImg: "", smallImg: [] };
        },
        // 视频上传成功处理
        handleVideoSuccess(res, file, fileList) {
            console.log("上传");
            console.log(fileList);
            this.uploadVideo.fileList = fileList;
        },
        //撤销视频上传（更改）
        handleVideoRemove() {
            // this.playerOptions.sources[0].src = this.service.videoUrl != '' ? this.baseUrl + this.service.videoUrl : '';
            // this.playerOptions.sources[0].name = this.service.videoUrl != '' ? this.service.videoUrl : '';
            this.playerOptions.sources[0].src = '';
            this.playerOptions.sources[0].name = '';
            this.uploadVideo.fileList = [];
        },
        //视频选择超出限制
        handleVideoExceed() {
            this.$modal.msgWarning("请先撤销再上传")
        },
        // 封面图上传成功处理
        handleCoverImgSuccess(res, file, fileList) {
            this.uploadCoverImg.fileList = fileList;
        },
        //撤销封面图上传（更改）
        handleCoverImgRemove() {
            this.uploadCoverImg.currentImg = this.service.serviceCoverImg;
            this.uploadCoverImg.fileList = [];
        },
        //封面图选择超出限制
        handleCoverImgExceed() {
            this.$modal.msgWarning("仅能选择上传一个视频")
        },
        // 轮播图上传成功处理
        handleSwiperImgSuccess(res, file, fileList) {
            this.uploadSwiperImg.fileList = fileList;
        },
        //撤销轮播图上传（更改）
        handleSwiperImgRemove(file) {
            console.log(file);
            //根据上传文件删除图片
            if (file.response) {
                this.uploadSwiperImg.fileList = this.uploadSwiperImg.fileList.filter(function (item) {
                    return item.uid !== file.uid;
                })
                this.uploadSwiperImg.currentImgs = this.uploadSwiperImg.currentImgs.filter(function (item) {
                    return item !== file.response.fileName;
                })
            }
            //根据图片路径删除图片 
            else if (file.constructor === String) {
                this.uploadSwiperImg.currentImgs = this.uploadSwiperImg.currentImgs.filter(function (item) {
                    return item !== file;
                })
                this.uploadSwiperImg.fileList = this.uploadSwiperImg.fileList.filter(function (item) {
                    return item.response.fileName !== file;
                })
            }
            //重置按钮
            else {
                this.uploadSwiperImg.fileList = [];
                this.uploadSwiperImg.currentImgs = JSON.parse(JSON.stringify(this.service.swiperImgUrls));
            }
        },
        // 详情图上传成功处理
        handleDetailImgSuccess(res, file, fileList) {
            this.uploadDetailImg.fileList = fileList;
        },
        //撤销详情图上传（更改）
        handleDetailImgRemove(file) {
            console.log(file);
            //根据上传文件删除图片
            if (file.response) {
                this.uploadDetailImg.fileList = this.uploadDetailImg.fileList.filter(function (item) {
                    return item.uid !== file.uid;
                })
                this.uploadDetailImg.currentImgs = this.uploadDetailImg.currentImgs.filter(function (item) {
                    return item !== file.response.fileName;
                })
            }
            //根据图片路径删除图片 
            else if (file.constructor === String) {
                this.uploadDetailImg.currentImgs = this.uploadDetailImg.currentImgs.filter(function (item) {
                    return item !== file;
                })
                this.uploadDetailImg.fileList = this.uploadDetailImg.fileList.filter(function (item) {
                    return item.response.fileName !== file;
                })
            }
            //重置按钮
            else {
                this.uploadDetailImg.fileList = [];
                this.uploadDetailImg.currentImgs = JSON.parse(JSON.stringify(this.service.serviceDetailsUrls));
            }
        },
        //撤销精品推荐展示大图上传
        handleReBigImgRemove() {
            this.service.recommendationImg.bigImg = "";
        },
        //撤销精品推荐展示小图2上传
        handleReSmallImg1Remove() {
            this.$set(this.service.recommendationImg.smallImg, 0, "");
        },
        //撤销精品推荐展示小图2上传
        handleReSmallImg2Remove() {
            this.$set(this.service.recommendationImg.smallImg, 1, "");
        },
        //撤销热门推荐展示图上传
        handleHotImgRemove() {
            this.service.popularServicesImg = "";
        },
        //上传
        handleUpload(httpParams) {
            let that = this;
            let type = httpParams.data.type;
            if (this.$refs[type]) {
                this.$refs[type].loading = true;
            }
            uploadImgPre(httpParams.file.name, "standardsImg").then(res => {
                uploadImgToCloud(res.data, httpParams.file).then(result => {
                    that.handleUploadSuccess(httpParams.data, res);
                    that.$modal.msgSuccess("上传成功");
                    if (this.$refs[type]) {
                        that.$refs[type].loading = false;
                    }
                })
            })
        },
        //上传成功分类处理
        handleUploadSuccess(typeParams, res) {
            switch (typeParams.type) {
                case "video":
                    this.playerOptions.sources[0].src = this.baseUrl + "/" + res.data.key;
                    this.playerOptions.sources[0].name = "/" + res.data.key;
                    break;
                case "detailsImg":
                    this.uploadDetailImg.currentImgs.push("/" + res.data.key);
                    break;
                case "coverImg":
                    this.uploadCoverImg.currentImg = "/" + res.data.key;
                    break;
                case "swiperImg":
                    this.uploadSwiperImg.currentImgs.push("/" + res.data.key);
                    break;
                case "recommendationImg":
                    if (typeParams.size == "b") {
                        this.service.recommendationImg.bigImg = "/" + res.data.key;
                        break;
                    }
                    if (typeParams.size == "s1") {
                        this.$set(this.service.recommendationImg.smallImg, 0, "/" + res.data.key);
                        break;
                    }
                    if (typeParams.size == "s2") {
                        this.$set(this.service.recommendationImg.smallImg, 1, "/" + res.data.key);
                        break;
                    }
                case "popularImg":
                    this.service.popularServicesImg = "/" + res.data.key;
                    break;
            }
        },
        //保存服务
        submit() {
            //视频、图片更新
            this.service.videoUrl = this.playerOptions.sources[0].name;
            this.service.serviceCoverImg = this.uploadCoverImg.currentImg;
            this.service.swiperImgUrls = this.uploadSwiperImg.currentImgs;
            this.service.serviceDetailsUrls = this.uploadDetailImg.currentImgs;
            this.service.serviceTime = this.serviceTime ? 1 : 0;
            if (this.service.serviceId != undefined) {
                updateService(this.service).then(res => {
                    this.submitService();
                    this.$modal.msgSuccess("修改成功");
                })
            } else {
                addService(this.service).then(response => {
                    this.submitService();
                    this.$modal.msgSuccess("新增成功");
                });
            }


        },
        //重置服务
        reset() {
            this.service = JSON.parse(JSON.stringify(this.oldService));
            this.initService();
        },
        //计算所选服务时长
        getTime(index) {
            return this.service.serviceTimeStart / 1 + this.service.serviceTimeStep * index / 1;
        },
    },
    watch: {
        serviceParams(e) {
            this.service = e;
            this.initService();
        }
    }
}
</script>
<style>
.service_container {
    height: calc(100vh - 84px);
    overflow-y: scroll;
}
</style>